import React, { PureComponent } from 'react'
import Link from 'umi/link'
import { Popover, Tooltip } from 'antd'
import classNames from 'classnames'
import { Icon } from 'react-fa'
import Menu from './Menu'
import pathToRegexp from 'path-to-regexp'
import { check } from '@/components/Authorized'

const getIcon = icon => {
  if (typeof icon === 'string') {
    return <Icon name={icon} />;
  }
  return icon;
};

const urlToList = (url) => {
	const urllist = url.split('/').filter(i => i);
	return urllist.map((urlItem, index) => `/${urllist.slice(0, index + 1).join('/')}`);
}
const getMenuMatches = (flatMenuKeys, path) =>
	flatMenuKeys.filter(item => {
		if (item) {
			return pathToRegexp(item).test(path);
		}
		return false;
	});

const { Item } = Menu

export default class SystemMenu extends PureComponent {
	state = {
		visible: false
	};
	static defaultProps = {
		prefixCls: 'menu'
	}
	getMenu = data => {
		return (data || [])
		.filter(item => !item.hide && item.system)
		.map(item => this.getSubMenuOrItem(item))
	};
	getSubMenuOrItem = item => {
		return <Item key={item.path}><Link to={item.path} className="ico-nav" onClick={e => {this.setState({ visible: false })}} replace>{getIcon(item.icon)}<span className="ico-text">{item.name}</span></Link></Item>
	};
	getSelectedMenuKeys = pathname => {
		const {
			flatMenuKeys
		} = this.props;
		return urlToList(pathname).map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop()).filter(item => item);
	};
	handleVisibleChange = visible => {
		this.setState({ visible });
	}
	render() {
		const {
			visible
		} = this.state
		const {
			user: {
				authorities = []
			},
			menu,
			location: {
				pathname
			}
		} = this.props

		const selectedKeys = this.getSelectedMenuKeys(pathname)

		const subMenus = <Menu 
					selectedKeys={selectedKeys}>{this.getMenu(menu)}</Menu>

		return check(authorities)('ORG_VIEW', 'USER_VIEW', 'ROLE_VIEW', 'LOG_VIEW') ?  (
			<ul>
				<Popover 
					placement="rightBottom" 
					content={subMenus} 
					visible={visible} 
					trigger="click"
					onVisibleChange={this.handleVisibleChange}
				>
					<Tooltip title="系统" placement="right">
						<li className={classNames({
								[`hover`]: selectedKeys.length > 0
							})}
							>
							<span className="ico-nav">{getIcon("gears")}<span className="ico-text">系统</span></span>
						</li>
					</Tooltip>
				</Popover>
			</ul>
		) : null
	}
}